// pages/uploading_img/uploading_img.js
const app = getApp()
var util = require("../../utils/utils.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    liveComment: "",
    texts: "至少10个字",
    min: 10,
    max: 24,
    showModalStatus: false,
    page: 1,
    dateIndex: 0,
    imageList: [],
    itemList: []
  },
  delimg: function(e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  //字数限制  
  inputs: function(e) {
    // 获取输入框的内容
    var value = e.detail.value;
    // 获取输入框内容的长度
    var len = parseInt(value.length);

    //最少字数限制
    if (len <= this.data.min)
      this.setData({})
    else if (len > this.data.min)
      this.setData({
        liveComment: value
      })

    //最多字数限制
    if (len > this.data.max) return;
    // 当输入框内容的长度大于最大长度限制（max)时，终止setData()的执行
    this.setData({
      currentWordNumber: len //当前字数  
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: "图片上传"
    })
    this.loadActInfo();
  },
  loadActInfo: function () {
    var that = this;
    wx.request({
      url: app.httpUrl +'/activity/queryActList',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        page: 1,
        rows: 40
      },
      success: (res) => {
        if (res.data.code == '000') {
          that.setData({
            actList: res.data.data.results
          })
        }
      }
    })
  },
  queryValidAttachList: function() {
    var that = this;
    wx.request({
      url: app.httpUrl + '/activity/live/queryValidAttachList',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "post",
      data: {
        operatorId: this.data.activity.hmSignId,
        attachType: 'image',
        relationType: 'live'
      },
      success: (res) => {
        if (res.data.code == '000') {
          if (res.data.data != null) {
            that.setData({ imageList: res.data.data })
          }
        }
      }
    })
  },
  pickerAct: function (e) {
    var idx = e.detail.value;
    this.setData({
      dateIndex: idx
    })
  },
  queryActImageList: function () {
    // 活动图片
    let that = this;
    wx.request({
      url: app.httpUrl + '/activity/live/queryMyResource',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        hmSignId: this.data.activity.hmSignId,
        page: that.data.page,
        rows: 4,
        liveType: "image",
      },
      method: "POST",
      success: (res) => {
        if (that.data.page >= res.data.data.totalPage) {
          that.setData({
            isOver: true
          })
        }
        that.data.page += 1;
        var itemList = that.data.itemList;
        var list = res.data.data.results;
        for (var i in list) {
          for (var j in list[i].attachList) {
            if (j == 0) {
              list[i].firstImg = app.imgUrl + list[i].attachList[j].attachUrl;
            }
            list[i].attachList[j].attachUrl = app.imgUrl + list[i].attachList[j].attachUrl;
          }
          itemList.push(list[i]);
        }
        that.setData({
          itemList: itemList
        })
      }
    })
  },
  loadMore: function() {
    this.queryActImageList();
  },
  delActivityLive: function(event) {
    var id = event.currentTarget.dataset.key;
    var that = this;
    wx.showModal({
      title: '删除组图片',
      content: '确认删除此组图片?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.httpUrl + '/activity/live/delActivityLive',
            header: {
              'xcx-xtoken': app.globalData.openid,
              'content-type': 'application/json' // 默认值
            },
            method: "post",
            data: {
              id: id
            },
            success: (res) => {
              if (res.data.code == '000') {
                var itemList = that.data.itemList;
                for (var i in itemList) {
                  if (itemList[i].id == id) {
                    itemList.splice(i, 1);
                    break;
                  }
                }
                if (res.data.data != null) {
                  that.setData({ itemList: itemList })
                }
              }
            }
          })
        } else if (res.cancel) {

        }
      }
    })
  },
  delAttach: function (event) {
    var id = event.currentTarget.dataset.key;
    var that = this;

    wx.showModal({
      title: '删除图片',
      content: '确认删除此图片?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.httpUrl + '/activity/live/delActivityAttach',
            header: {
              'xcx-xtoken': app.globalData.openid,
              'content-type': 'application/json' // 默认值
            },
            method: "post",
            data: {
              id: id
            },
            success: (res) => {
              if (res.data.code == '000') {
                var imageList = that.data.imageList;
                for (var i in imageList) {
                  if (imageList[i].id == id) {
                    imageList.splice(i, 1);
                    break;
                  }
                }
                if (res.data.data != null) {
                  that.setData({ imageList: imageList })
                }
              }
            }
          })
        } else if (res.cancel) {

        }
      }
    })
  },
  wxChooseImage: function (e) {
    var that = this;
    var count = this.data.imageList;
    wx.chooseImage({
      count: 9 - count, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        var data = { paths: tempFilePaths};
        wx.showLoading({
          title: '上传中...',
        })
        that.uploadImage(data);
      }
    })
  },
  uploadImage: function(data) {
    var that = this,
    i = data.i ? data.i : 0,//当前上传的哪张图片
    success = data.success ? data.success : 0,//上传成功的个数
    fail = data.fail ? data.fail : 0;//上传失败的个数
    wx.uploadFile({
      url: app.httpUrl + '/activity/live/addActivityAttch',
      filePath: data.paths[i],
      name: 'file',
      formData: {
        'activityId': that.data.activity.activityId,
        'attachType': 'image',
        'operatorId': that.data.activity.hmSignId
      },
      header: {
        'xcx-xtoken': app.globalData.openid,
        "content-type": "multipart/form-data"
      },
      success: function (res) {
        var model = JSON.parse(res.data);
        if (model.code == '000') {
          success++;
          var imageList = that.data.imageList;
          imageList.push(model.data);
          that.setData({ imageList: imageList})
        }
      },
      fail: function (res) {
        fail++;
      },
      complete: function(res) {
        i++;
        if (i == data.paths.length) {   //当图片传完时，停止调用      
          console.log('执行完毕');
          console.log('成功：' + data.success + " 失败：" + data.fail);
          wx.hideLoading();
        }else {//若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadImage(data);
        }
      }
    })
  },
  addActivityLive: function() {
    var that = this;
    var liveComment = this.data.liveComment;
    if (liveComment.length < 10) {
      wx.showToast({
        title: '描述内容不少于10个字',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if(this.data.imageList.length < 6) {
      wx.showToast({
        title: '图片不少于6张',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.request({
      url: app.httpUrl + '/activity/live/addActivityLive',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "post",
      data: {
        liveComment: this.data.liveComment,
        liveType: 'image',
        activityId: this.data.actList[this.data.dateIndex].id,
        isChoice: 1
      },
      success: (res) => {
        if (res.data.code == '000') {
          wx.showToast({ title: '提交成功！', icon: 'success', duration: 3000 });
          that.setData({
            liveComment: '',
            imageList: [],
            itemList: [],
            page: 1,
            isOver: false
          })
          that.queryActImageList();
        }else {
          wx.showToast({ title: "提交失败!", icon: 'none', duration: 3000 });
        }
      }
    })
  },
  previewImage: function (event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var list = this.data.imageList;
    var urls = [];
    for (var i in list) {
      urls.push(app.imgUrl + list[i].attachUrl);
    }
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: urls // 需要预览的图片http链接列表     
    })
  },
  previewItemImage: function (event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var idx = event.currentTarget.dataset.idx;
    var list = this.data.itemList[idx].attachList;
    var urls = [];
    for (var i in list) {
      urls.push(list[i].attachUrl);
    }
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: urls // 需要预览的图片http链接列表     
    })
  },
})